package co.dreamapps.dodoattack.model;


import org.andengine.input.touch.TouchEvent;

public class MoveDetector {

	/**
	 * Constants
	 */
	public static final int NONE = 0;
	public static final int MOVE_UP = 1;
	public static final int MOVE_DOWN = 2;
	public static final int MOVE_LEFT = 4;
	public static final int MOVE_RIGHT = 8;

	/**
	 * Entities
	 */
	private int moveType;
	public int getMoveType() {return moveType;}
	private int initialX, initialY;
	private long lastPress;
	private static final int MAXIMUM_MOVE_DURATION = 300;
	private static final int MINIMUM_MOVE_DIFERENCE = 120;

	/**
	 * Constructor
	 */
	public MoveDetector() {
		moveType = NONE;
	}
	
	/**
	 * Methods
	 */
	public int touch(TouchEvent touchEvent) {
		if(touchEvent.isActionDown()) {
			this.initialX = (int) touchEvent.getX();
			this.initialY = (int) touchEvent.getY();
			this.lastPress = System.currentTimeMillis();
		} else if(touchEvent.isActionUp() && (System.currentTimeMillis() - lastPress) < MAXIMUM_MOVE_DURATION) {
			int difX = (int) Math.abs(initialX - touchEvent.getX());
			int difY = (int) Math.abs(initialY - touchEvent.getY());
			if(difX > difY) {
				if(difX > MINIMUM_MOVE_DIFERENCE) {
					moveType = initialX - touchEvent.getX() > 0 ? MOVE_LEFT : MOVE_RIGHT;
					return (int) touchEvent.getY();
				}
			} else {
				if(difY > MINIMUM_MOVE_DIFERENCE) {
					moveType = initialY - touchEvent.getY() > 0 ? MOVE_DOWN : MOVE_UP;
					return (int) touchEvent.getX();
				}
			}
		} else {
			moveType = NONE;
		}
		return -1;
	}
}
